﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Data.SqlClient;
using System.Diagnostics;
using HenIT.BizTalk;
using btom = Microsoft.BizTalk.ExplorerOM;

namespace HenIT.BizTalk
{
    public partial class MainForm : Form
    {
        public MainForm()
        {
            InitializeComponent();
        }

        private void MainForm_Load(object sender, EventArgs e)
        {
            try
            {
                if (!File.Exists(Properties.Settings.Default.BTSTask))
                {
                    MessageBox.Show("BTSTask.exe not found! Please verify location of executable and update config file.", "BTSTask", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    lblBTSTask.ForeColor = Color.Red;
                    cmdExport.Enabled = false;
                }

                lblBTSTask.Text = Properties.Settings.Default.BTSTask;
                txtExportDir.Text = Properties.Settings.Default.ExportDir;
                if (Properties.Settings.Default.LastMgmtServer == null || Properties.Settings.Default.LastMgmtServer.Length == 0)
                    Properties.Settings.Default.LastMgmtServer = BizTalkUtils.GetCurrentBizTalkSqlServer();
                txtMgmtServer.Text = Properties.Settings.Default.LastMgmtServer;
                if (Properties.Settings.Default.LastMgmtDb == null || Properties.Settings.Default.LastMgmtDb.Length == 0)
                    Properties.Settings.Default.LastMgmtDb = BizTalkUtils.GetCurrentBizTalkMgmtDb();
                txtMgmtDb.Text = Properties.Settings.Default.LastMgmtDb;
                chkExportType.SelectedIndex = 0;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void lblBTSTask_Click(object sender, EventArgs e)
        {
            openFileDialogBTSTaskExec.FileName = Properties.Settings.Default.BTSTask;
            if (openFileDialogBTSTaskExec.ShowDialog() == DialogResult.OK)
            {
                Properties.Settings.Default.BTSTask = openFileDialogBTSTaskExec.FileName;
                Properties.Settings.Default.Save();
                lblBTSTask.ForeColor = SystemColors.ControlText;
                cmdExport.Enabled = true;
            }
        }

        private void cmdLoadApps_Click(object sender, EventArgs e)
        {
            //string sql = "SELECT nvcName FROM bts_application";
            try
            {
                lvwApps.Items.Clear();
                using (btom.BtsCatalogExplorer catalog = new btom.BtsCatalogExplorer())
                {
                    catalog.ConnectionString = "SERVER=" + txtMgmtServer.Text + ";DATABASE=" + txtMgmtDb.Text + ";Integrated Security=SSPI";
                    foreach (btom.Application application in catalog.Applications)
                    {
                        if (!application.IsSystem)
                        {
                            ListViewItem lvi = new ListViewItem(application.Name);
                            lvwApps.Items.Add(lvi);
                        }
                    }
                    
                }



                //string connStr = "Server=" + txtMgmtServer.Text + ";Database=" + txtMgmtDb.Text + ";Trusted_Connection=True;";
                //using (SqlConnection conn = new SqlConnection(connStr))
                //{
                //    conn.Open();
                //    using (SqlCommand cmnd = new SqlCommand(sql, conn))
                //    {
                //        using (SqlDataReader dr = cmnd.ExecuteReader())
                //        {
                //            while (dr.Read())
                //            {
                //                if (dr[0].ToString() != "BizTalk.System")
                //                {
                //                    ListViewItem lvi = new ListViewItem(dr[0].ToString());
                //                    lvwApps.Items.Add(lvi);
                //                }
                //            }
                //        }
                //    }
                //}
                Properties.Settings.Default.LastMgmtServer = txtMgmtServer.Text;
                Properties.Settings.Default.LastMgmtDb = txtMgmtDb.Text;
                Properties.Settings.Default.Save();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void lstApps_SelectedValueChanged(object sender, EventArgs e)
        {

        }

        private bool itemSelfCheck = false;
        private void chkSelectAll_CheckedChanged(object sender, EventArgs e)
        {
            if (!itemSelfCheck)
            {
                itemSelfCheck = true;
                for (int i = 0; i < lvwApps.Items.Count; i++)
                {
                    lvwApps.Items[i].Checked = chkSelectAll.Checked;
                }
                itemSelfCheck = false;
            }
        }

        private void lvwApps_ItemChecked(object sender, ItemCheckedEventArgs e)
        {
            bool allChecked = true;
            if (!itemSelfCheck)
            {
                itemSelfCheck = true;
                for (int i = 0; i < lvwApps.Items.Count; i++)
                {
                    if (!lvwApps.Items[i].Checked)
                    {
                        allChecked = false;
                    }
                }

                chkSelectAll.Checked = allChecked;

                itemSelfCheck = false;
            }
        }

        private void cmdExport_Click(object sender, EventArgs e)
        {
            string batchCmnd = "";
            string exportDir = txtExportDir.Text.TrimEnd('\\');
            if (!Directory.Exists(txtExportDir.Text))
            {
                MessageBox.Show("Directory " + txtExportDir.Text + " does not exist!", "Export directory", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
            else
            {
                batchCmnd = "";
                if ((chkExportType.SelectedIndex == 0) || (chkExportType.SelectedIndex == 2))
                {
                    foreach (ListViewItem lvi in lvwApps.CheckedItems)
                    {
                        batchCmnd += "BTSTask ExportApp /ApplicationName:\"" + lvi.Text + "\" /Package:\"" + exportDir + "\\" + lvi.Text + ".msi\" /Server:" + txtMgmtServer.Text + " /Database:" + txtMgmtDb.Text + "\r\n";
                    }

                    StreamWriter output = File.CreateText(exportDir + "\\BTSExportApps.cmd");
                    output.Write(batchCmnd);
                    output.Flush();
                    output.Close();
                    Process btsExportAppsProcess = Process.Start(exportDir + "\\BTSExportApps.cmd");
                    btsExportAppsProcess.WaitForExit();
                }

                batchCmnd = "";
                if ((chkExportType.SelectedIndex == 1) || (chkExportType.SelectedIndex == 2))
                {
                    foreach (ListViewItem lvi in lvwApps.CheckedItems)
                    {
                        batchCmnd += "BTSTask ExportBindings -ApplicationName:\"" + lvi.Text + "\" -Destination:\"" + exportDir + "\\" + lvi.Text + ".BindingInfo.xml\" /Server:" + txtMgmtServer.Text + " /Database:" + txtMgmtDb.Text + "\r\n";
                    }

                    StreamWriter output = File.CreateText(exportDir + "\\BTSExportBindings.cmd");
                    output.Write(batchCmnd);
                    output.Flush();
                    output.Close();
                    Process.Start(exportDir + "\\BTSExportBindings.cmd");
                }
            }
        }

        private void cmdBrowseExportDir_Click(object sender, EventArgs e)
        {
            folderBrowserDialogExportDir.SelectedPath = txtExportDir.Text;
            if (folderBrowserDialogExportDir.ShowDialog() == DialogResult.OK) 
            {
                txtExportDir.Text = folderBrowserDialogExportDir.SelectedPath;
                Properties.Settings.Default.ExportDir = txtExportDir.Text;
                Properties.Settings.Default.Save();
            }
        }

        private void MainForm_Resize(object sender, EventArgs e)
        {
            lvwApps.Columns [0].Width = lvwApps.Width - 25;
        }

    }
}
